package com.platform.modules.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.platform.common.utils.StringUtils;
import com.platform.modules.ncp.entity.NcpCumulativeOfCasesEntity;
import com.platform.modules.ncp.entity.NcpPersonInfoEntity;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.Servlet;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName ExcelUtil
 * @Description TODO
 * @Author TuMin
 * @Date 2020/2/12 9:50
 */
public class ExcelUtil {

    public static Workbook exportPersonInfo(List<NcpPersonInfoEntity> personInfoEntities) {
        // 加载模板
        TemplateExportParams params = new TemplateExportParams("templates/personinfotemp.xlsx");
        Map<String,Object> map = new HashMap<>();
        map.put("date",new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date()));
        List<Map<String,Object>> list = new ArrayList<>();
        AtomicInteger i = new AtomicInteger(1);
        personInfoEntities.forEach(personInfo -> {
            Map<String,Object> tempMap = new HashMap<>();
            tempMap.put("no",i.toString());
            tempMap.put("persName",personInfo.getPersName());
            tempMap.put("street",personInfo.getStreet());
            tempMap.put("community",personInfo.getCommunity());
            tempMap.put("address",personInfo.getAddress());
            tempMap.put("idNumber",personInfo.getIdNumber());
            tempMap.put("contact",personInfo.getContact());
            tempMap.put("diagnosis",personInfo.getDiagnosis());
            tempMap.put("hospital",personInfo.getHospital());
            tempMap.put("illState",personInfo.getIllState());
            tempMap.put("rna",personInfo.getRna());
            tempMap.put("remark",personInfo.getRemark());
            list.add(tempMap);
            i.getAndIncrement();
        });
        map.put("dataList",list);
        // 生成workbook
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        return workbook;
    }

    public static Workbook exportCumulative(List<NcpCumulativeOfCasesEntity> cumulativeOfCasesEntities) {
        // 加载模板
        TemplateExportParams params = new TemplateExportParams("templates/cumulativetemplate.xlsx");
        Map<String,Object> map = new HashMap<>();
        map.put("date",new SimpleDateFormat("MM.dd").format(new Date()));
        map.put("street",cumulativeOfCasesEntities.get(0).getStreet());
        List<Map<String,Object>> list = new ArrayList<>();
        AtomicInteger i = new AtomicInteger(1);
        cumulativeOfCasesEntities.forEach(cumulative -> {
            Map<String,Object> tempMap = new HashMap<>();
            tempMap.put("no",i.toString());
            tempMap.put("persName",cumulative.getPersName());
            tempMap.put("idNumber",cumulative.getIdNumber());
            tempMap.put("sex",cumulative.getSex()==1?"男":cumulative.getSex()==2?"女":"未知");
            tempMap.put("age",cumulative.getAge());
            tempMap.put("contact",cumulative.getContact());
            tempMap.put("street",cumulative.getStreet());
            tempMap.put("address",cumulative.getAddress());
            tempMap.put("casesClassification",cumulative.getCasesClassification()==1?"疑似病例":cumulative.getCasesClassification()==2?"确诊病例":"临床病例");
            tempMap.put("reportedUnit",cumulative.getReportedUnit());
            tempMap.put("clinicalSeverity",cumulative.getClinicalSeverity());
            tempMap.put("whereAboutsIn",cumulative.getWhereAboutsIn());
            tempMap.put("modifyAddress",cumulative.getModifyAddress());
            tempMap.put("remarks",cumulative.getRemark());
            list.add(tempMap);
            i.getAndIncrement();
        });
        map.put("dataList",list);
        // 生成workbook
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        return workbook;
    }


    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);

    }
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new ApiException(e.getMessage());
        }
    }
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new ApiException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(e.getMessage());
        }
        return list;
    }
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new ApiException("excel文件不能为空");
        } catch (Exception e) {
            throw new ApiException(e.getMessage());
        }
        return list;
    }

//    public static void main(String[] args) {
//        String path = "D:\\development\\temp\\2.xls";
//        List<NcpCumulativeOfCasesEntity> list = importExcel(path,1,1,NcpCumulativeOfCasesEntity.class);
//        System.out.println("共解析"+list.size()+"条数据，第5条的患者叫"+list.get(4).getPersName());
//    }

}
